package YBClient

import (
	"strconv"
	"youbei/dao"
	"youbei/utils/jobs"

	"github.com/beego/beego/httplib"

	"github.com/gin-gonic/gin"
)

type updatelogStruct struct {
	Strs []string `json:"json"`
	Log  dao.Log  `json:"log"`
}

func RunJob(c *gin.Context) {
	task := dao.Task{}
	if err := c.Bind(&task); err != nil {
		APIReturn(c, 500, "解析失败", err)
		return
	}

	if err := backup(&task); err != nil {
		APIReturn(c, 500, "执行失败", err)
		return
	}
	APIReturn(c, 200, "成功", nil)
}

func backup(task *dao.Task) error {
	wl, err := getwl()
	if err != nil {
		return err
	}

	var log dao.Log
	log.ID = task.LogId

	var cols []string
	localfilepath, err := jobs.ExecBackup(task)
	if err != nil {
		cols = append(cols, "status", "msg")
		log.Status = 2
		log.Msg = err.Error()
		postLog(wl, &log, cols)
		return err
	}
	cols = append(cols, "localfilepath")
	log.Localfilepath = localfilepath
	cols = append(cols, "status")
	log.Status = 0
	postLog(wl, &log, cols)

	if len(task.RemoteStorages) > 0 {
		for _, v := range task.RemoteStorages {
			jobs.ExecuteRemoteFileTransfer(v, localfilepath, log.ID, wl)
		}
	}

	return nil
}

type respLog struct {
	Cols []string `json:"cols"`
	Log  dao.Log  `json:"log"`
}

func postLog(wl dao.Whitelist, log *dao.Log, cols []string) {
	replog := respLog{}
	req := httplib.Post("http://" + wl.ServerIP + ":" + strconv.Itoa(wl.ServerPort) + "/client/updatelog")
	req.Header("token", wl.Token)
	req.Header("Content-Type", "application/json")
	replog.Cols = cols
	replog.Log = *log
	req.JSONBody(replog)
	req.String()
}
